﻿using HelixToolkit.Wpf.SharpDX.Assimp;
using System;
using System.Collections.Generic;
using System.Linq;
using WpfModelEditor.Core.Plugins;

namespace AssimpIoPlugin
{
    public class AssimpPlugin : IIoPlugin
    {
        public AssimpPlugin()
        {
            SupportedImportFormats = HelixToolkit.Wpf.SharpDX.Assimp.Importer.SupportedFormats.Select(p =>
            {
                return new IoFormat
                {
                    Name = p,
                    Ext = p
                };
            }).ToList();
            SupportedExportFormats = HelixToolkit.Wpf.SharpDX.Assimp.Exporter.SupportedFormats.Select(p =>
            {
                return new IoFormat
                {
                    Name = p.Description,
                    Ext = "." + p.FileExtension
                };
            }).ToList();
        }
        public List<IoFormat> SupportedImportFormats { get; set; }

        public List<IoFormat> SupportedExportFormats { get; set; }

        public int Order => 10000;

        public void Clearup()
        {
        }

        public void Initialize(IHost host)
        {
        }

        public LoadSaveResult Load(string path, string ext, out Scene scene)
        {
            scene = null;

            var loader = new Importer();
            /*
            loader.Configuration.CreateSkeletonForBoneSkinningMesh = true;
            loader.Configuration.SkeletonSizeScale = 0.04f;
            loader.Configuration.GlobalScale = 0.1f;*/
            HelixToolkitScene s;

            var err = loader.Load(path, out s);

            if (loader.ErrorCode != ErrorCode.Succeed)
                throw new Exception($"加载文件失败: {loader.ErrorCode}");
            scene = new Scene
            {
                Root = s.Root,
                Animations = s.Animations.ToList()
            };
            return LoadSaveResult.Success;
        }

        public LoadSaveResult Save(string path, string ext, Scene scene)
        {
            foreach(var format in HelixToolkit.Wpf.SharpDX.Assimp.Exporter.SupportedFormats)
            {
                if("."+format.FileExtension == ext)
                {
                    var exporter = new HelixToolkit.Wpf.SharpDX.Assimp.Exporter();
                    var ret = exporter.ExportToFile(path, new HelixToolkitScene(scene.Root, scene.Animations), format.FormatId);
                    if (ret != ErrorCode.Succeed)
                        return LoadSaveResult.Error;
                    return LoadSaveResult.Success;
                }
            }
            return LoadSaveResult.NotSupport;
        }
    }
}
